from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import PostForm

    
def post_list(request):
    posts = Post.objects.all().order_by('-created_on')
    return render(request, 'post_list.html', {'posts': posts})

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'post_detail.html', {'post': post})

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            # 获取表单中作者的名字
            post.author = form.cleaned_data['author']
            post.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            # 获取表单中作者的名字
            post.author = form.cleaned_data['author']
            post.save()
            return redirect('post_list')
    else:
        form = PostForm(instance=post)
    return render(request, 'post_edit.html', {'form': form})

def post_delete(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.delete()
    return redirect('post_list')

def post_search(request):
    query = request.GET.get('q')
    if not query:
        return redirect('no_results')
    posts = Post.objects.filter(title__icontains=query) | Post.objects.filter(body__icontains=query).order_by('-created_on')
    if not posts:
        return redirect('no_results')
    return render(request, 'post_list.html', {'posts': posts})

def no_results(request):
    return render(request, 'no_results.html', {'message': '抱歉，我们未能找到与您的搜索查询匹配的文章。'})